package com.example.myui.adapter;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.myui.MainActivity;
import com.example.myui.R;
import com.example.myui.model.ApkModel;
import com.example.myui.utils.NotifyUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/2/1/001.
 */

public class MultiDownAdapter extends BaseQuickAdapter<ApkModel, BaseViewHolder> {
    private Context mContext;
    private static final String TAG = MultiDownAdapter.class.getSimpleName();
    private List<ApkModel> apkModels = new ArrayList<>();

    private final NumberFormat numberFormat;
    public static final int TYPE_ALL = 0;
    public static final int TYPE_FINISH = 1;
    public static final int TYPE_ING = 2;
    private int type;
    private List<DownloadTask> values;
    private Intent service = null;
    private NotifyUtil notifyUtil;
    //    private List<DownloadTask> tasks = new ArrayList<>();

    public MultiDownAdapter(Context context, @Nullable List<ApkModel> data) {
        super(R.layout.item_down_load, data);
        this.mContext = context;
        this.apkModels = data;

        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);
    }

    @Override
    protected void convert(BaseViewHolder holder, ApkModel item) {
        Glide.with(mContext)
                .load(item.iconUrl)
                .into((ImageView) holder.getView(R.id.imageView));
        holder.setText(R.id.textView, item.name);
//        holder.setText(R.id.textView2, "speed");
        Button start = holder.getView(R.id.button2);
        Button pause = holder.getView(R.id.button3);
        Button delete = holder.getView(R.id.button4);
        Button restart = holder.getView(R.id.button5);
        TextView tasks = holder.getView(R.id.textView5);
        /*
        * 显示所有的任务数
        * */
        tasks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int size = values.size();
                for (int i = 0; i < size; i++) {
                    Log.i(TAG, "onClick: " + values.get(i).progress.fileName);
                }
            }
        });
        /*
        * 开始下载
        * */
        start.setOnClickListener(new View.OnClickListener() {

            private Notification.Builder builder;

            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: " + values.size());
//                updateData(TYPE_ALL);
                if (OkDownload.getInstance().hasTask(apkModels.get(holder.getLayoutPosition()).url)) {
                    OkDownload.getInstance().removeTask(apkModels.get(holder.getLayoutPosition()).url);
                }
                GetRequest<File> file = OkGo.<File>get(apkModels.get(holder.getLayoutPosition()).url);
                DownloadTask task = OkDownload.request(apkModels.get(holder.getLayoutPosition()).url, file)
                        .folder(Environment.getExternalStorageDirectory() + "/apkdown/")
                        .fileName(apkModels.get(holder.getLayoutPosition()).name + ".apk")
                        .save()
                        .register(new DownloadListener(holder.getLayoutPosition() + "") {
                            @Override
                            public void onStart(Progress progress) {
//                                //开启下载服务显示通知栏
//                                service = new Intent(mContext, DownloadService.class);
//                                service.putExtra("progress", progress);
//                                mContext.startService(service);
//                                发送一个通知
//                                sendNotification(mContext,progress);
                                notifyUtil = new NotifyUtil(mContext);
                                PendingIntent activity = PendingIntent.getActivity(mContext, 0, new Intent(mContext, MainActivity.class), PendingIntent.FLAG_ONE_SHOT);
                                notifyUtil.creatNotify(R.mipmap.ic_launcher,
                                        R.mipmap.ic_launcher,
                                        progress.fileName,
                                        progress.fileName,
                                        "正在下载。。。",
                                        activity,
                                        holder.getLayoutPosition(),
                                        0
                                );
                                Log.i(TAG, "onStart: " + "-------------->start");
                            }

                            @Override
                            public void onProgress(Progress progress) {
//                                if (null == service) {
//                                    service = new Intent(mContext, DownloadService.class);
//                                    service.putExtra("progress", progress);
//                                    mContext.startService(service);
//                                }

                                notifyUtil.updateNotify(holder.getLayoutPosition(), (int) (progress.fraction * 100));
                                holder.setText(R.id.textView2, numberFormat.format(progress.fraction));
                                String speed = Formatter.formatFileSize(mContext, progress.speed);
                                holder.setText(R.id.textView3, String.format("%s/s", speed));
                                holder.setText(R.id.textView4, (int) (progress.totalSize / 1024 / 1024) + "");
//                                holder.speed.setText(String.format("%s/s", speed));
//                                holder.size.setText((int) (progress.totalSize / 1024 / 1024) + "");
                            }

                            @Override
                            public void onError(Progress progress) {
                                Toast.makeText(mContext, "errot:" + progress.status, Toast.LENGTH_SHORT).show();
                                Log.i(TAG, "onError: " + progress.status + "------------->");
                                //停止服务
//                                mContext.stopService(service);
                            }

                            @Override
                            public void onFinish(File file, Progress progress) {
                                Toast.makeText(mContext, "onFinisd:" + file.getName(), Toast.LENGTH_SHORT).show();
                                updateData(MultiDownAdapter.TYPE_ALL);
                                //停止服务
//                                mContext.stopService(service);
                            }

                            @Override
                            public void onRemove(Progress progress) {

                            }
                        });

//                tasks.add(task);
                task.start();
            }
        });
        /*
        * 暂定下载
        * */
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (OkDownload.getInstance().hasTask(apkModels.get(holder.getLayoutPosition()).url)) {
                }
                DownloadTask task = OkDownload.getInstance().getTask(apkModels.get(holder.getLayoutPosition()).url)
                        .register(new DownListener(holder));
                int status = task.progress.status;
                switch (status) {
                    case Progress.PAUSE:
                    case Progress.NONE:
                    case Progress.ERROR:
                        task.start();
                        pause.setText("暂停");
                        break;
                    case Progress.LOADING:
                        task.pause();
                        pause.setText("继续下载");
                        break;
                    case Progress.FINISH:
//                        if (ApkUtils.isAvailable(context, new File(progress.filePath))) {
//                            ApkUtils.uninstall(context, ApkUtils.getPackageName(context, progress.filePath));
//                        } else {
//                            ApkUtils.install(context, new File(progress.filePath));
//                        }
                        break;
                }

            }
        });
        /*
        * 删除任务
        * */
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                tasks.get(holder.getLayoutPosition()).remove(true);
                values.get(holder.getLayoutPosition()).remove(true);
            }
        });
        /*
        * 重新开始任务
        * */
        restart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                tasks.get(holder.getLayoutPosition()).restart();
//                if (OkDownload.getInstance().hasTask(apkModels.get(holder.getLayoutPosition()).url)){
//                    OkDownload.getInstance().removeTask(apkModels.get(holder.getLayoutPosition()).url);
//                }
            }
        });
    }

    private void sendNotification(Context mContext, Progress progress) {
        Notification.Builder builder = new Notification.Builder(mContext);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentTitle("郭嘉");
        builder.setContentText("我们打袁绍吧");
        //设置Notification.Default_ALL(默认启用全部服务(呼吸灯，铃声等)
        builder.setDefaults(Notification.DEFAULT_ALL);
        //调用NotificationCompat.Builder的setContentIntent()来添加PendingIntent
        Intent intent = new Intent(mContext, MainActivity.class);
        intent.putExtra("info", "郭嘉给你发了一个计策！");
        PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pi);
        //获取Notification
        Notification n = builder.build();
        //通过NotificationCompat.Builder.build()来获得notification对象自己
        NotificationManager manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        //然后调用NotificationManager.notify()向系统转交
        manager.notify(1, n);

    }

    public void updateData(int typeAll) {
        //这里是将数据库的数据恢复
        this.type = typeAll;
        if (type == TYPE_ALL) values = OkDownload.restore(DownloadManager.getInstance().getAll());
        if (type == TYPE_FINISH)
            values = OkDownload.restore(DownloadManager.getInstance().getFinished());
        if (type == TYPE_ING)
            values = OkDownload.restore(DownloadManager.getInstance().getDownloading());
        notifyDataSetChanged();
    }

    private class DownListener extends DownloadListener {
        public DownListener(Object tag) {
            super(tag);
        }

        @Override
        public void onStart(Progress progress) {

        }

        @Override
        public void onProgress(Progress progress) {
            refreshUI(progress);
        }

        @Override
        public void onError(Progress progress) {

        }

        @Override
        public void onFinish(File file, Progress progress) {

        }

        @Override
        public void onRemove(Progress progress) {

        }
    }

    private void refreshUI(Progress progress) {

    }
}
